import websocket from '../../utils/websocket';

Page({
  data: {
    messages: [],
    inputContent: '',
    productInfo: null,
    otherUserInfo: null,
    userInfo: wx.getStorageSync('userInfo'),
    scrollToMessage: null,
    sessionId: null
  },

  async onLoad(options) {
    const { productId, userId, sessionId } = options;
    const token = wx.getStorageSync('token');

    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          wx.navigateTo({ url: '/pages/login/login' });
        }
      });
      return;
    }

    // 根据是否有sessionId判断是否是首次聊天
    if (sessionId) {
      // 从消息列表进入，直接加载已有会话
      console.log('加载已有会话:', sessionId);
      this.setData({ sessionId });
      await this.initExistingChat(sessionId);
    } else {
      // 从商品详情页进入，需要初始化新会话
      console.log('初始化新会话, productId:', productId, 'userId:', userId);
      await this.initNewChat(productId, userId);
    }
  },

  // 初始化新的聊天会话
  async initNewChat(productId, userId) {
    return new Promise((resolve, reject) => {
      // 设置统一的消息处理器
      websocket.onMessage((data) => {
        console.log('聊天页面收到消息(新聊天):', data);
        const { type, data: messageData } = data;

        switch (type) {
          case 'chatInitiated':
            // 处理初始化数据
            console.log('收到聊天初始化数据:', messageData);
            websocket.setSessionId(messageData.sessionId);
            this.setData({
              sessionId: messageData.sessionId,
              productInfo: messageData.product,
              otherUserInfo: messageData.seller
            });
            wx.setNavigationBarTitle({
              title: messageData.seller.name
            });
            // 初始化完成后加载历史消息
            this.loadHistoryMessages();
            resolve();
            break;

          case 'history':
            // 处理历史消息
            console.log('收到历史消息:', messageData);
            const historyMessages = messageData.messages || [];
            const formattedHistory = historyMessages.map(msg => this.formatMessage(msg));
            this.setData({ messages: formattedHistory });
            break;

          case 'messageSent':
            // 处理发送的消息
            console.log('收到发送的消息:', messageData);
            const sentMessage = this.formatMessage(messageData);
            console.log('格式化后的发送消息:', sentMessage);
            const updatedMessages = [...this.data.messages, sentMessage];
            console.log('更新后的消息列表长度:', updatedMessages.length);
            this.setData({
              messages: updatedMessages,
              scrollToMessage: `msg-${sentMessage.id}`
            });
            break;

          case 'messageReceived':
            // 处理接收的消息
            console.log('收到接收的消息:', messageData);
            const receivedMessage = this.formatMessage(messageData);
            const updatedMessagesReceived = [...this.data.messages, receivedMessage];
            this.setData({
              messages: updatedMessagesReceived,
              scrollToMessage: `msg-${receivedMessage.id}`
            });
            break;

          case 'error':
            // 处理错误
            console.error('收到错误消息:', messageData);
            wx.showToast({
              title: messageData.message || '发生错误',
              icon: 'none'
            });
            break;
        }
      });

      // 连接WebSocket并初始化聊天
      if (!websocket.isConnected) {
        websocket.connect();
      }

      // 发起聊天初始化
      websocket.initChat(productId).catch(error => {
        console.error('初始化聊天失败:', error);
        reject(error);
      });
    });
  },

  // 初始化已存在的聊天会话
  async initExistingChat(sessionId) {
    return new Promise((resolve, reject) => {
      // 设置消息处理器
      websocket.onMessage((data) => {
        console.log('聊天页面收到消息(已有会话):', data);
        const { type, data: messageData } = data;

        switch (type) {
          case 'history':
            // 处理历史消息
            console.log('收到历史消息:', messageData);
            const historyMessages = messageData.messages || [];
            const formattedHistory = historyMessages.map(msg => this.formatMessage(msg));
            this.setData({
              messages: formattedHistory,
              productInfo: messageData.product,
              otherUserInfo: messageData.otherUser
            });
            wx.setNavigationBarTitle({
              title: messageData.otherUser.name
            });
            resolve();
            break;

          case 'messageSent':
            // 处理发送的消息
            console.log('收到发送的消息(已有会话):', messageData);
            const sentMessage = this.formatMessage(messageData);
            console.log('格式化后的发送消息:', sentMessage);
            const updatedMessages = [...this.data.messages, sentMessage];
            console.log('更新后的消息列表长度:', updatedMessages.length);
            this.setData({
              messages: updatedMessages,
              scrollToMessage: `msg-${sentMessage.id}`
            });
            break;

          case 'messageReceived':
            // 处理接收的消息
            console.log('收到接收的消息(已有会话):', messageData);
            const receivedMessage = this.formatMessage(messageData);
            const updatedMessagesReceived = [...this.data.messages, receivedMessage];
            this.setData({
              messages: updatedMessagesReceived,
              scrollToMessage: `msg-${receivedMessage.id}`
            });
            break;

          case 'error':
            // 处理错误
            console.error('收到错误消息:', messageData);
            wx.showToast({
              title: messageData.message || '发生错误',
              icon: 'none'
            });
            break;
        }
      });

      // 连接WebSocket
      if (!websocket.isConnected) {
        websocket.connect();
      }

      // 设置会话ID并加载历史消息
      websocket.setSessionId(sessionId);
      this.loadHistoryMessages();
    });
  },

  // 格式化消息
  formatMessage(msg) {
    const userInfo = this.data.userInfo;
    console.log('格式化消息, 用户信息:', userInfo, '消息信息:', msg);

    // 确保消息中有sender和receiver
    if (!msg.sender || !msg.receiver) {
      console.error('消息缺少发送者或接收者信息:', msg);
      return {
        id: msg.id || Date.now().toString(),
        content: msg.content || '',
        timestamp: msg.createdAt || new Date(),
        isSelf: true, // 默认为自己发送的
        senderName: userInfo.name || '我',
        receiverName: '对方',
        sender: msg.sender || userInfo,
        receiver: msg.receiver || {},
        type: msg.type || 'text'
      };
    }

    // 使用ID比较确定是否是自己的消息
    const isSelf = msg.sender.id === userInfo._id;
    console.log('是否是自己的消息:', isSelf, '发送者ID:', msg.sender.id, '用户ID:', userInfo._id);

    return {
      id: msg.id,
      content: msg.content,
      timestamp: msg.createdAt,
      isSelf: isSelf,
      senderName: msg.sender.name,
      receiverName: msg.receiver.name,
      sender: msg.sender,
      receiver: msg.receiver,
      type: msg.type
    };
  },

  async loadHistoryMessages() {
    try {
      const response = await websocket.getHistory();
      console.log('历史消息响应:', response);

      const historyMessages = response.data.messages || [];
      // 对消息进行排序，确保按时间正序显示（旧消息在前，新消息在后）
      const sortedMessages = historyMessages.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
      const messages = sortedMessages.map(msg => this.formatMessage(msg));

      this.setData({ messages });
    } catch (error) {
      console.error('加载历史消息失败：', error);
      wx.showToast({
        title: '加载历史消息失败',
        icon: 'none'
      });
    }
  },

  // 发送消息
  async sendMessage() {
    const { inputContent } = this.data;
    if (!inputContent) return;

    console.log('准备发送消息:', inputContent);

    try {
      // 发送前先显示一个临时消息（本地消息）
      const tempId = `temp_${Date.now()}`;
      const tempMessage = {
        id: tempId,
        content: inputContent,
        timestamp: new Date(),
        isSelf: true,
        senderName: this.data.userInfo.name || '我',
        receiverName: this.data.otherUserInfo ? this.data.otherUserInfo.name : '对方',
        sender: this.data.userInfo,
        receiver: this.data.otherUserInfo || {},
        type: 'text',
        isTemp: true
      };

      // 更新UI以立即显示
      const updatedMessages = [...this.data.messages, tempMessage];
      this.setData({
        messages: updatedMessages,
        inputContent: '',
        scrollToMessage: `msg-${tempId}`
      });

      console.log('已添加临时消息:', tempMessage);

      // 实际发送消息
      await websocket.sendMessage(inputContent);
      console.log('消息发送成功');
    } catch (error) {
      console.error('发送消息失败:', error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
    }
  },

  onInputChange(e) {
    this.setData({
      inputContent: e.detail.value
    });
  },

  onInputBlur(e) {
    this.setData({
      inputContent: e.detail.value
    });
  },

  scrollToBottom() {
    wx.createSelectorQuery()
      .select('#message-list')
      .boundingClientRect((rect) => {
        if (rect) {
          wx.pageScrollTo({
            scrollTop: rect.height,
            duration: 300
          });
        }
      })
      .exec();
  },

  onUnload() {
    // 清理所有消息处理器
    if (websocket.ws) {
      // 重置消息处理器为null
      websocket.onMessage(null);
    }
  },

  // 格式化日期
  formatDate(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === today.toDateString()) {
      return '今天';
    } else if (date.toDateString() === yesterday.toDateString()) {
      return '昨天';
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  }
}) 